import { Controller, Post, Body, Get, Put, Delete, Param, UseGuards, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { LoginService } from './login.service';
import { RegisterDto, LoginDto, ChangePasswordDto } from './dto/login.dto';
import { CreateDeviceDto, UpdateDeviceDto } from './dto/device.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';



@ApiTags('登录模块')
@Controller('api/logins')
export class LoginController {

  private readonly logger = new Logger(LoginController.name);

  constructor(private readonly loginService: LoginService) {}

  @Post('register')
  @ApiOperation({ summary: '用户注册' })
  @ApiResponse({ status: 201, description: '注册成功' })
  @ApiResponse({ status: 409, description: '用户名已存在' })
  @ApiResponse({ status: 401, description: '用户不在白名单中或已被禁用' })
  async register(@Body() registerDto: RegisterDto): Promise<void> {
    const errors = await validate(plainToClass(RegisterDto, registerDto));
    if (errors.length > 0) {
      this.logger.error(`Validation failed for register: ${JSON.stringify(errors)}`);
      throw new Error('Invalid input');
    }
    this.logger.log(`Registering user with data: ${JSON.stringify(registerDto)}`);
    await this.loginService.register(registerDto);
    this.logger.log('User registered successfully');
  }

  @Post('login')
  @ApiOperation({ summary: '用户登录' })
  @ApiResponse({ status: 200, description: '登录成功' })
  @ApiResponse({ status: 401, description: '用户名或密码错误' })
  async login(@Body() loginDto: LoginDto) {
    const errors = await validate(plainToClass(LoginDto, loginDto));
    if (errors.length > 0) {
      this.logger.error(`Validation failed for login: ${JSON.stringify(errors)}`);
      throw new Error('Invalid input');
    }
    this.logger.log(`Logging in user with data: ${JSON.stringify(loginDto)}`);
    const result = await this.loginService.login(loginDto);
    this.logger.log('User logged in successfully');
    return result;
  }

  @Put('change-password')
  // @UseGuards(JwtAuthGuard)
  // @ApiBearerAuth()
  @ApiOperation({ summary: '修改密码' })
  @ApiResponse({ status: 200, description: '密码修改成功' })
  @ApiResponse({ status: 401, description: '旧密码错误' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async changePassword(
    @Body() changePasswordDto: ChangePasswordDto,
    @Param('userId') userId: string,
  ): Promise<void> {
    const errors = await validate(plainToClass(ChangePasswordDto, changePasswordDto));
    if (errors.length > 0) {
      this.logger.error(`Validation failed for change password: ${JSON.stringify(errors)}`);
      throw new Error('Invalid input');
    }
    this.logger.log(`Changing password for user ${userId} with data: ${JSON.stringify(changePasswordDto)}`);
    await this.loginService.changePassword(userId, changePasswordDto);
    this.logger.log('Password changed successfully');
  }

  @Post('devices')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '创建设备' })
  @ApiResponse({ status: 201, description: '设备创建成功' })
  async createDevice(@Body() createDeviceDto: CreateDeviceDto) {
    const errors = await validate(plainToClass(CreateDeviceDto, createDeviceDto));
    if (errors.length > 0) {
      this.logger.error(`Validation failed for create device: ${JSON.stringify(errors)}`);
      throw new Error('Invalid input');
    }
    this.logger.log(`Creating device with data: ${JSON.stringify(createDeviceDto)}`);
    const result = await this.loginService.createDevice(createDeviceDto);
    this.logger.log('Device created successfully');
    return result;
  }

  @Get('devices')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取所有设备' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async findAllDevices() {
    this.logger.log('Fetching all devices');
    const result = await this.loginService.findAllDevices();
    this.logger.log('All devices fetched successfully');
    return result;
  }

  @Get('devices/:id')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取指定设备' })
  @ApiResponse({ status: 200, description: '获取成功' })
  @ApiResponse({ status: 404, description: '设备不存在' })
  async findDeviceById(@Param('id') id: string) {
    this.logger.log(`Fetching device with id: ${id}`);
    const result = await this.loginService.findDeviceById(id);
    this.logger.log('Device fetched successfully');
    return result;
  }

  @Put('devices/:id')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '更新设备' })
  @ApiResponse({ status: 200, description: '更新成功' })
  @ApiResponse({ status: 404, description: '设备不存在' })
  async updateDevice(
    @Param('id') id: string,
    @Body() updateDeviceDto: UpdateDeviceDto,
  ) {
    const errors = await validate(plainToClass(UpdateDeviceDto, updateDeviceDto));
    if (errors.length > 0) {
      this.logger.error(`Validation failed for update device: ${JSON.stringify(errors)}`);
      throw new Error('Invalid input');
    }
    this.logger.log(`Updating device with id: ${id} and data: ${JSON.stringify(updateDeviceDto)}`);
    const result = await this.loginService.updateDevice(id, updateDeviceDto);
    this.logger.log('Device updated successfully');
    return result;
  }

  @Delete('devices/:id')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '删除设备' })
  @ApiResponse({ status: 200, description: '删除成功' })
  @ApiResponse({ status: 404, description: '设备不存在' })
  async deleteDevice(@Param('id') id: string) {
    this.logger.log(`Deleting device with id: ${id}`);
    await this.loginService.deleteDevice(id);
    this.logger.log('Device deleted successfully');
  }
}